import {
    URL_CAPITAL_HISTORY,
    URL_CAPITAL_LIST,
    URL_CAPITAL_TRANSACTIONS,
    URL_CLEVER,
    URL_CLEVER_CAPITAL,
    URL_CLEVER_CAPITAL_COINS,
    URL_CLEVER_CAPITAL_POSITION,
    URL_LAST_ACTIVE,
    URL_PERSON_AMOUNT,
    URL_PERSON_COINS,
    URL_PERSON_DETAIL,
    URL_PERSON_HISTORY,
    URL_PERSON_POSITION,
    URL_PERSON_TRANSACTIONS,
    URL_TOKEN_DATA
} from "@/comm/api";
import { get } from "@/comm/request";
import { sortList } from "@/comm/tooler";
import { defineStore } from "pinia";
import { useClever } from "./clever";
import { Bus, PERSON_CHANEG } from "@/connetion/Bus";

const clever = useClever();

interface IState {
    detail: any;
    blockBalanceList: Array<any>;
    curblockBalance: any;
    curCapital: any;
    capitalList: Array<any>;
    positions: Array<any>;
    prevPositions: Array<any>;
    transactions: Array<any>;
    transactionCurPage: number;
    transactionPageSize: number;
    transactionsTotal: number;
    transactionsTimestamp: number;
    historyAmount: Array<any>;
    historyInterval: string;
    klineDataList: Array<any>;
    day1Var: number;
    day7Var: number;
    totalAmount: number;
    id: string;
    actTime: number;
    positionLoading: boolean
}

export const usePerson = defineStore("person", {
    state: (): IState => ({
        detail: null,
        blockBalanceList: [],
        curblockBalance: null,
        curCapital: null,
        capitalList: [],
        positions: [],
        prevPositions: [],
        transactions: [],
        transactionCurPage: 1,
        transactionPageSize: 10,
        transactionsTotal: 0,
        transactionsTimestamp: 0,
        historyAmount: [],
        historyInterval: "W",
        klineDataList: [],
        day1Var: 0,
        day7Var: 0,
        totalAmount: 0,
        id: "",
        actTime: 0,
        positionLoading: false
    }),

    getters: {
        totalPage(): number {
            return Math.ceil(this.transactionsTotal / this.transactionPageSize);
        }
    },
    actions: {
        async changeCurblockBalance(val: any) {
            console.log("change CurblockBalance", val);
            this.transactionsTimestamp = 0;
            this.curblockBalance = val;
            await this.loadTransaction();
            await this.loadKlineData();
        },
        async start(id: string) {
            await this.loadCapitals();
            await this.init(id);
        },
        async init(id: string) {
            // let url = URL_PERSON_DETAIL.replace("@", id);
            this.id = id;

            let res: any = await get(URL_PERSON_DETAIL, { tokenAddress: id });
            this.detail = res.data;
            this.curCapital = res.data;
            if(!res.data?.capitalInfoId){
                this.detail.capitalInfoId = id;
            }

            let url = URL_PERSON_COINS.replace("@", id);
            res = await get(url);
            console.warn("币种-------", res);
            this.blockBalanceList = res.data;

            this.changeCurblockBalance(this.blockBalanceList[0]);
            this.loadPosition(Date.now());
            // this.loadLastTime();
            // this.loadHistory();
            this.loadAmount(id);
        },
        async loadAmount(id: string) {
            let url = URL_PERSON_AMOUNT.replace("@", id);
            let res: any = await get(url);
            if (res.data) {
                this.day1Var = res.data.currentTotalBalance - res.data.yesterdayTotalBalance;
                this.day7Var = res.data.currentTotalBalance - res.data.lastTimeBalance;
                this.totalAmount = res.data.currentTotalBalance;
                this.actTime = res.data.timestamp;
            }
        },

        async loadLastTime() {
            let res: any = await get(URL_LAST_ACTIVE.replace("@", this.id));
            this.actTime = res.data.lastTime;
        },
        async loadCapitals() {
            this.positionLoading = true;
            let res: any = await get(URL_CAPITAL_LIST);
            this.capitalList = res.data;
        },
        async changeCurCapital(val: any) {
            // this.detail = val;
            // this.curCapital = val;
            console.log("切換機構", val);
            await this.init(val.capitalInfoId);
        },
        changeTransactionsTimestamp(val: number) {
            this.transactionsTimestamp = val;
        },
        async loadPosition(timer: number) {
            this.positions = [];
            let url = URL_PERSON_POSITION.replace("@", this.id);
            // var t = new Date("2023-11-01 23:59:59");
            url = url + "?timestamp=" + timer;
            let res: any = await get(url);
            console.log("倉位信息", res);
            this.positions = res.data?.todayList || [];
            this.prevPositions = res.data?.yesterdayList || [];
            // this.positions = res.data || [];
            // await this.loadPrevPosition(timer);
            this.positionLoading = false;
        },

        async loadPrevPosition(timer: number) {
            this.prevPositions = [];
            let url = URL_PERSON_POSITION.replace("@", this.id);
            // var t = new Date("2023-11-01 23:59:59");
            url = url + "?timestamp=" + (timer - 24 * 60 * 60 * 1000);
            let res: any = await get(url);
            console.log("倉位信息", res);
            this.prevPositions = res.data || [];
        },
        async togglePage(page: number) {
            this.transactionCurPage = page;
            this.loadTransaction();
        },
        async loadTransaction() {
            this.transactions = [];
            const param: any = {
                current: this.transactionCurPage,
                size: this.transactionPageSize,
                capitalId: this.detail.capitalInfoId,
                contractAddress: this.curblockBalance.contractAddress,
                address: this.id
            };
            if (this.transactionsTimestamp) {
                param.timestamp = this.transactionsTimestamp;
            }
            let res: any = await get(URL_PERSON_TRANSACTIONS, param);
            console.log("交易信息", res);
            this.transactions = res.data?.records || [];
            this.transactionsTotal = res.data?.total || 0;
        },
        async loadHistory() {
            let url = URL_PERSON_HISTORY.replace("@", this.id);
            let param: any = {};
            if (this.historyInterval !== "ALL") {
                param.type = this.historyInterval;
            }
            const res: any = await get(url, param);
            console.log("機構歷史", res);
            if (res.wait) {
                setTimeout(() => {
                    this.loadHistory();
                }, 2000);
                return;
            }

            let ary = res.data || [];
            sortList(ary, "timestamp", false);
            this.historyAmount = ary;

            // if (this.historyInterval == "W") {
            //     let t = this.historyAmount.length;
            //     if (this.historyAmount && this.historyAmount[t - 1]) {
            //         this.day1Var = this.historyAmount[t - 1].balance - this.historyAmount[t - 2].balance;
            //         this.day7Var = this.historyAmount[t - 1].balance - this.historyAmount[0].balance;
            //         this.totalAmount = this.historyAmount[t - 1].balance;
            //     }
            // }
        },
        async changeHistoryInterval(val: string) {
            this.historyInterval = val;
            this.loadHistory();
        },
        async loadKlineData() {
            console.log("clever.interval", clever.interval);
            Bus.emit(PERSON_CHANEG, "kline");
            let param = {
                token: this.curblockBalance.contractAddress,
                type: clever.interval || "D"
            };
            let res: any = await get(URL_TOKEN_DATA, param);
            let list = res.data ? res.data : [];
            let aim = list.map((i: any, idx: number) => {
                return i;
                // let n = Number(i.priceUSD);
                // let open = idx > 0 ? Number(list[idx - 1].priceUSD) : n;
                // let max = Math.max(open, n);
                // let min = Math.min(open, n)
                // return {
                //     timestamp: i.date * 1000,
                //     open: open,
                //     close: n,
                //     low: min,
                //     volume: 0,
                //     high: max,
                //     // color: "#00ff00"
                // }
            });

            sortList(aim, "timestamp", false);
            this.klineDataList = aim;
        }
    }
});

function accountOneDay(item: any) {
    if (item && item.position && item.position.length) {
        return item.position.reduce((a: any, b: any) => a + b.usd, 0);
    }
    return 0;
}
